package com.example.new6.views;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import com.example.new6.R;
import com.example.new6.client.ApiClient;

public class DictActivity extends AppCompatActivity implements ApiClient.OnDataListener {
    private TextView textViewHanzi;
    private TextView textViewPinyin;
    private TextView textViewBihua;
    private TextView textViewBushou;
    private TextView textViewWords;
    private TextView textViewBasic;
    private TextView textViewDetail;
    private EditText sourceText;
    private Button queryButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dict);

        sourceText = findViewById(R.id.source_text);
        queryButton = findViewById(R.id.query_button);
        textViewHanzi = findViewById(R.id.hanzi);
        textViewPinyin = findViewById(R.id.pinyin);
        textViewBihua = findViewById(R.id.bihua);
        textViewBushou = findViewById(R.id.bushou);
        textViewWords = findViewById(R.id.words);
        textViewBasic = findViewById(R.id.basic_explain);
        textViewDetail = findViewById(R.id.detail_explain);
        queryButton = findViewById(R.id.query_button);

        ApiClient apiClient = new ApiClient();
        apiClient.setOnDataListener(this);
        queryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入框中的文本
                String textToQuery = sourceText.getText().toString();
                // 调用 fetchData 方法进行查询
                apiClient.fetchData(DictActivity.this, "https://api.oioweb.cn/api/txt/dict?text=" + textToQuery, DictActivity.this);
            }
        });
    }

    @Override
    public void onDataReceived(String hanzi, String pinyin, String bihua, String bushou, String words, String basicExplain, String detailExplain) {
        runOnUiThread(() -> {
            textViewHanzi.setText("汉字: " + hanzi);
            textViewPinyin.setText("拼音: " + pinyin);
            textViewBihua.setText("笔画: " + bihua);
            textViewBushou.setText("部首: " + bushou);
            textViewWords.setText("组词: " + words);
            textViewBasic.setText( basicExplain);
            textViewDetail.setText( detailExplain);
        });
    }

    @Override
    public void onUrlReceived(String url) {
        runOnUiThread(() -> {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        });
    }
}